package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.gexiaobao.flowlayout.FlowLayout
import com.gexiaobao.flowlayout.TagAdapter
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.FragmentMallSearchGoodsBinding
import com.gexiaobao.pigeon.ui.fragment.mall.db.RecordsDao
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.util.Timer
import java.util.TimerTask


/**
 * @Author      : hxw
 * @Date        : 2023/6/12 16:07
 * @Describe    : 搜索商品
 */
class FragmentSearchGoods : BaseFragment<MallViewModel, FragmentMallSearchGoodsBinding>() {

    private var mRecordsDao: RecordsDao? = null

    //默认展示词条个数
    private val defaultRecordNumber = 10
    private var recordList: ArrayList<String> = arrayListOf()
    private var mRecordsAdapter: TagAdapter<*>? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        //默认账号
        val username = "007"
        //初始化数据库
        mRecordsDao = RecordsDao(context, username)
        //获取edittext焦点 并弹出软键盘
        showSoftInputFromWindow(mDatabind.editQuery)
        initDaoData()
        initTagLayout()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvSearchGoods, mDatabind.ivBack) {
            when (it) {
                mDatabind.tvSearchGoods -> {
                    searchGoodsBtn()
                }

                mDatabind.ivBack -> {
                    nav().navigateUp()
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.goodsListResult.observe(viewLifecycleOwner) {
//            loadListData(it, mAdapter, loadsir, swipeRecyclerView, swipeRefreshLayout)
        }
    }

    private fun searchGoodsBtn() {
        val record: String = mDatabind.editQuery.text.toString()
        if (!TextUtils.isEmpty(record)) {
            //添加数据
            mRecordsDao!!.addRecords(record)
        }
        mViewModel.getAppGoodList("", record, "")
        nav().navigateAction(R.id.action_to_fragment_search_result, Bundle().apply {
            putString("searchContent", record)
            putString("type", "0")
        })
    }

    private fun initTagLayout() {
        //创建历史标签适配器 为标签设置对应的内容
        mRecordsAdapter = object : TagAdapter<String?>(recordList as List<String?>?) {
            override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                val tv = LayoutInflater.from(context).inflate(
                    R.layout.tv_history,
                    mDatabind.tagFlowLayoutHistory, false
                ) as TextView
                //为标签设置对应的内容
                tv.text = t
                return tv
            }

        }
    }

    override fun initData() {
        super.initData()
        mDatabind.tagFlowLayoutHistory.adapter = mRecordsAdapter

        mDatabind.tagFlowLayoutHistory.setOnTagClickListener { _, position, _ ->
            //清空editText之前的数据
            mDatabind.editQuery.setText("")
            //将获取到的字符串传到搜索结果界面,点击后搜索对应条目内容
            mDatabind.editQuery.setText(recordList[position])
            mDatabind.editQuery.setSelection(mDatabind.editQuery.length())
            searchGoodsBtn()
            true
        }

        //删除某个条目
        mDatabind.clearAllRecords.setOnLongClickListener {
            showDialog(getString(R.string.market_shop_search_activity_sure_delete_record)) { _, _ -> //删除某一条记录
                //删除某一条记录
                mRecordsDao?.deleteRecord(it.id)
            }
            true
        }

        //清除所有记录
        mDatabind.clearAllRecords.setOnClickListener {
            showDialog(getString(R.string.market_shop_search_activity_sure_delete_record_all)) { _, _ ->
                //清除所有数据
                mRecordsDao!!.deleteUsernameAllRecords()
                mDatabind.tagFlowLayoutHistory.isLimit = true
            }
        }

        mRecordsDao!!.setNotifyDataChanged { initDaoData() }

        mDatabind.editQuery.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                if (!TextUtils.isEmpty(mDatabind.editQuery.text.toString())) {
                    RxToast.showToast("搜索的是:" + mDatabind.editQuery.text.toString())
                    searchGoodsBtn()
                } else {
                    RxToast.showToast("请输入需要搜索的内容")
                }
                hideSoftKeyboard(activity)
            }
            false
        }
    }

    @SuppressLint("CheckResult")
    private fun initDaoData() {
        Observable.create { emitter -> emitter.onNext(mRecordsDao!!.getRecordsByNumber(defaultRecordNumber)) }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                recordList.clear()
                recordList = it as ArrayList<String>
                if (mRecordsAdapter != null) {
                    mRecordsAdapter!!.setData(recordList as List<Nothing>?)
                    mRecordsAdapter!!.notifyDataChanged()
                }
            }
    }

    private fun showDialog(dialogTitle: String, onClickListener: DialogInterface.OnClickListener) {
        val builder: AlertDialog.Builder = context?.let { AlertDialog.Builder(it) }!!
        builder.setMessage(dialogTitle)
        builder.setPositiveButton(R.string.sure, onClickListener)
        builder.setNegativeButton(R.string.cancel, null)
        builder.create().show()
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    private fun showSoftInputFromWindow(editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        Timer().schedule(object : TimerTask() {
            override fun run() {
                val inputMethodManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }, 200)
    }

    override fun onDestroyView() {
        mRecordsDao?.closeDatabase()
        mRecordsDao?.removeNotifyDataChanged()
        super.onDestroyView()
    }
}